program funcaoscreenshot;

{$mode objfpc}{$H+}

uses
  Classes,
  // Qt4
  qt4,
  // X11
  x, xlib, xrender, xcomposite, xfixes, xutil, xatom;

procedure TakeXCompositeScreenshot();
var
  FileVar: TextFile;
  cont : Integer = 0;
  w      : Widestring;
  Pixmap: QPixmapH;
  pix: longword  ;
  depth, j, n, x2 ,y,height, width, major, minor, event_base, error_base  : integer;
  i:Longint;
  w1, w2, m_root : TWindow;
  wins: PWindow;
  layout : QGridLayoutH;
  QTimer : QTimerH;
  dpy : Pdisplay;
  windowatt: TXWindowAttributes;
  image : PXImage;
  hasNamePixmap, bool : Boolean;
  hasAlpha : Longint;
  format : PXRenderPictFormat;
  pa : PXRenderPictureAttributes;
  picture: Tpicture;
  nome: PWideString;
begin
  dpy := XOpenDisplay(nil);
  m_root := XRootWindow(dpy, XDefaultScreen(dpy));
  hasNamePixmap:=False;
  {
  if (XCompositeQueryExtension(dpy, @event_base, @error_base))  then
  begin
  major:=0;
  minor:=2;
  XCompositeQueryVersion(dpy, @major, @minor);

  if ((major>0)or(minor>=2)) then
  hasNamePixmap := True;
  end;
   }
 { XGetWindowAttributes(dpy , wins[16], @windowatt);
  windowatt.override_redirect:=1;
  XRaiseWindow(dpy, wins[16]);}


  XCompositeRedirectSubwindows(dpy, m_root, 1);


  format :=XRenderFindVisualFormat(dpy, DefaultVisual(dpy, DefaultScreen(dpy)));
  XQueryTree (dpy, m_root, @w1, @w2, @wins, @n);

  for i:=0 to n - 1 do
  begin
       XGetWindowAttributes(dpy , wins[i], @windowatt);
       windowatt.override_redirect:=1;

       if (((windowatt.map_state=1) and (windowatt.x>10)) or((windowatt.map_state=2) and (windowatt.x>10))) then
       begin

       format:=XRenderFindVisualFormat(dpy, windowatt.visual);

       x2:=windowatt.x;
       y:=windowatt.y;
       width:=windowatt.width;
       height:=windowatt.height;

      // pa.subwindow_mode:=IncludeInferiors;
       picture := XRenderCreatePicture (dpy, wins[i], format,CPSubWindowMode,@pa);
       pix := XCompositeNameWindowPixmap(dpy, wins[i]);

       //XRenderComposite(dpy, hasAlpha, PictOpOver, PictOpSrc, picture, None, pixmap.x11PictureHandle(), 0, 0,0,0,x2,y, width, height);

       QString_number(nome,i);
       QPixmap_save(pixmap, nome,'PNG',-1);
       end;
  end;
end;

begin
  TakeXCompositeScreenshot();
end.

